/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.modbusServer.api;

import com.ghgande.j2mod.modbus.ModbusCoupler;
import com.ghgande.j2mod.modbus.net.AbstractModbusListener;
import com.ghgande.j2mod.modbus.procimg.ProcessImage;
import com.ghgande.j2mod.modbus.procimg.Register;
import com.ghgande.j2mod.modbus.procimg.SimpleProcessImage;
import com.ghgande.j2mod.modbus.procimg.SimpleRegister;
import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.commonutils.redis.ex.JedisNotInitializeException;
import com.seari.modbusServer.SEmodbusListenerFactory;

import redis.clients.jedis.Jedis;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rainbow
 */
public class SimpleModbusServerApiImpl implements IModbusServerApi
{

    protected static Logger logger = LoggerFactory.getLogger(SimpleModbusServerApiImpl.class);
    
    @Override
    public void createServer(int unitID, int port, int poolSize, int regCount)
    {
        AbstractModbusListener listener = null;
        SimpleProcessImage spi;
        String connString = "tcp:127.0.0.1" + ":" + port;
        spi = new SimpleProcessImage(unitID);
        for (int i = 0; i < regCount; i++)
        {
            spi.addRegister(i, new SimpleRegister(0));
        }
        ModbusCoupler.getReference().setProcessImage(spi);
        ModbusCoupler.getReference().setMaster(false);
        try
        {
            listener = SEmodbusListenerFactory.createModbusListener(connString, poolSize);
            
            logger.info("server start at {} and poolSize is {}", port, poolSize);
        } catch (Exception ex)
        {
            logger.warn(ex.getMessage());
        }
        
    }
    
    @Override
    public void refreshRegister(List<Map> emcsList)
    {
        Jedis redisClient = null;
        try
        {
            redisClient = JedisUtilProxy.getJedis();
        } catch (JedisNotInitializeException ex)
        {
            logger.warn(ex.getMessage());
        }
        int startPos = 0;
        int endPos = (int) emcsList.get(emcsList.size() - 1).get("modbus_address");
        ProcessImage pi = ModbusCoupler.getReference().getProcessImage(1);
        Register[] registers = pi.getRegisterRange(startPos, endPos + 1);
        String tableName;// redis中hash的名字
        String key;// hash的key
        String value;// hash的value，也是modbus寄存器的value
        int j;// modbus寄存器的地址

        for (int i = 0; i < emcsList.size(); i++)
        {
            Map map = emcsList.get(i);
            tableName = (String) map.get("table_name");
            key = (int) map.get("actual_address") + "";
            j = (int) map.get("modbus_address");
            value = redisClient.hget(tableName, key);
            if ("".equals(value) || value == null)
            {
                value = "0";
            }
            registers[j].setValue(Integer.parseInt(value));
        }
        JedisUtilProxy.close(redisClient);
    }

    @Override
    public void refreshRegister(int position, int value)
    {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

	@Override
	public void refreshRegister(int unitID, int position, int value)
	{
		// TODO Auto-generated method stub
		
	}
    
}
